<template>
  <el-dialog
    :title="`${isCreate ? '添加' : '编辑'}经验等级`"
    :visible.sync="dialogVisible"
    class="dialog"
    width="360px">
    <el-form
      :model="formData"
      label-width="120px"
      ref="form"
      :rules="rules"
      size="small">
      <el-form-item label="等级名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="最低经验值" prop="minVal">
        <el-input-number v-model="formData.minVal" :controls="false"></el-input-number>
      </el-form-item>
      <el-form-item label="最高经验值" prop="maxVal">
        <el-input-number v-model="formData.maxVal" :controls="false"></el-input-number>
      </el-form-item>
    </el-form>
    <dialog-footer
      slot="footer"
      @cancel="dialogVisible = false"
      @confirm="confirm"
    />
  </el-dialog>
</template>
<script>
import { saveExperienceLevel, updateExperienceLevel } from '@/api/base-config';

export default {
  props: {
    initFormData: Object,
    isCreate: Boolean,
  },
  data() {
    return {
      formData: {
        ...this.initFormData,
      },
      dialogVisible: false,
      rules: {
        name: [{ required: true, message: '等级姓名不能为空', trigger: 'blur' }],
        minVal: [{ required: true, message: '最低经验值不能为空', trigger: 'blur' }],
        maxVal: [{ required: true, message: '最高经验值不能为空', trigger: 'blur' }],
      },
    };
  },
  watch: {
    initFormData(val) {
      this.formData = { ...val };
    },
  },

  methods: {
    confirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            if (this.isCreate) {
              await saveExperienceLevel(this.formData);
            } else {
              await updateExperienceLevel(this.formData);
            }
          } catch (err) {
            console.log(err);
          }
          this.dialogVisible = false;
          this.$emit('confirm', this.formData);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
  .dialog {
    ::v-deep .el-input__inner {
      width: 200px;
    }
  }
</style>
